package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.moyun.zbmy.zizhou.application.Cache;
import com.ruihang.generalibrary.utils.ListUtils;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseAccountActivity;
import com.moyun.zbmy.zizhou.beans.AccountBean;
import com.moyun.zbmy.zizhou.beans.AccountVo;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.AccountAdapter;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.DataUtils;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 公众号搜索
 */
public class AccountSearchActivity extends BaseAccountActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , AccountAdapter.OnAccountSubscribeClickListener, AccountAdapter.OnAccountClickListener {

    @BindView(R.id.input_key)
    protected EditText searchKey;
    @BindView(R.id.search_result_layout)
    protected LinearLayout searchResultLayout;
    @BindView(R.id.search_null_layout)
    protected RelativeLayout searchNullLayout;
    @BindView(R.id.refresh_layout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    public static final String INPUT_KEY = "input_key";
    private String inputKey;
    private AccountAdapter adapter;
    private int mPageNo = 0;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<AccountBean> dataList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("关注更多媒体号");
        inputKey = getIntent().getStringExtra(INPUT_KEY);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_search_account);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        searchKey.setText(inputKey);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRefreshLayout.autoRefresh();
        searchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = searchKey.getText().toString().trim();
//                if(TextUtils.isEmpty(str)){
//                    cleanBtn.setVisibility(View.GONE);
//                }else{
//                    cleanBtn.setVisibility(View.VISIBLE);
//                }
            }
        });
    }

    @Override
    public void onLoadMore() {
        mPageNo++;
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 0;
        mIsLoading = true;
        getData();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            inputKey = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(inputKey)) {
                toast("请输入关键词");
            } else {
                //TODO  搜索
                mRefreshLayout.autoRefresh();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void getData() {

        mIsLoading = true;
        String token = "";
        String userId = "";
        if (null != UserManager.getInstance().getUser()) {
            token = UserManager.getInstance().getUser().getToken();
            userId = UserManager.getInstance().getUser().getUserId();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("userId", userId);
        param.put("token", token);
        param.put("index", "" + mPageNo);
        param.put("capacity", "10");
        param.put("nodeId", Cache.getInstance().getSearchAccountNodeId());
        param.put("keyWord", inputKey);

        NetUtils.getNetAdapter().searchAccountList(getOwnerName(),   param, new AbsNetCallBack<AccountVo>(AccountVo.class) {
            @Override
            public void onSuc(AccountVo accountVo) {
                if (null!=accountVo&&ListUtils.isListValued(accountVo.getResultList())) {
                    dataList.addAll(accountVo.getResultList());
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
                if (mPageNo >= 1) {
                    mPageNo--;
                }
            }

            @Override
            public void onEnd() {
                onNetFinish();
                mIsLoading = false;
                initData();
                if (ListUtils.isListValued(dataList)) {
                    searchResultLayout.setVisibility(View.VISIBLE);
                    searchNullLayout.setVisibility(View.GONE);
                } else {
                    searchResultLayout.setVisibility(View.GONE);
                    searchNullLayout.setVisibility(View.VISIBLE);
                }
            }
        });

    }


    private void initData() {
        if (null == adapter) {
            adapter = new AccountAdapter(this, dataList, this, this);
            mRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(dataList);
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(mPageNo+1 >= mPageAll ? false : true);

    }

    @Override
    public void OnAccountClick(AccountBean bean) {
        //TODO 点击公众号
        Intent intent = new Intent(this, AccountDetailActivity.class);
        intent.putExtra(AccountDetailActivity.ACCOUNT_ID, bean.getFollowedId());
        startActivityForResult(intent, 1);
    }

    @Override
    public void OnSubscribeClick(AccountBean bean) {
        //TODO 关注、取消关注公众号
        for (int i = 0; i < dataList.size(); i++) {
            AccountBean da = (AccountBean) dataList.get(i);
            if (bean.getFollowedId().equalsIgnoreCase(da.getFollowedId())) {
                toAttentionClick(bean);
                break;
            }
        }
        setResult(RESULT_OK);
    }

    @OnClick(value = {R.id.title_top_back, R.id.cancel})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                onBackPressed();
                break;
            case R.id.cancel:
                onBackPressed();
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                mRefreshLayout.autoRefresh();
                setResult(RESULT_OK);
            }
        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param bean
     */
    private void toAttentionClick(final AccountBean bean) {
        if (bean.getFollowedStatus() == 1) {
            toUnAttentionAccount(bean.getFollowedId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    for (int i = 0; i < dataList.size(); i++) {
                        AccountBean da = (AccountBean) dataList.get(i);
                        if (bean.getFollowedId().equalsIgnoreCase(da.getFollowedId())) {
                            ((AccountBean) dataList.get(i)).setFollowedStatus(0);
                            adapter.setData(dataList);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
            });
        } else {
            toAttentionAccount(bean.getFollowedId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    for (int i = 0; i < dataList.size(); i++) {
                        AccountBean da = (AccountBean) dataList.get(i);
                        if (bean.getFollowedId().equalsIgnoreCase(da.getFollowedId())) {
                            ((AccountBean) dataList.get(i)).setFollowedStatus(1);
                            adapter.setData(dataList);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

}
